package demo;

import java.util.Arrays;

public class MyHeapSort {

    public static void main(String[] args) {
        int[] arr = {1,0,10,16,-1,5,-18};

        heapSort(arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    private static void heapSort(int[] arr, int left , int right) {
        // 边界条件：空数组或只有一个元素无需排序
        if (arr == null || arr.length <= 1) {
            return;
        }

        int n = arr.length;

        //构建大根堆
        for(int i = n / 2 -1; i >= 0; i--) {
            heapify(arr,n,i);
        }

        // 第二步：逐步提取最大值并调整堆
        for (int i = n - 1; i > 0; i--) {
            // 交换堆顶（最大值）和当前末尾元素
            swap(arr, 0, i);

            // 对剩余元素重新调整为大顶堆，堆大小减1
            heapify(arr, i, 0);
        }
    }

    private static void heapify(int[] arr, int heapSize, int i) {
        // 初始化最大值位置为当前节点
        int largest = i;
        //计算左右节点的索引
        int leftChild = 2 * i + 1 , rightChild = 2 * i + 2;

        if(leftChild < heapSize && arr[leftChild] > arr[largest]) {
            largest = leftChild;
        }
        if(rightChild < heapSize && arr[rightChild] > arr[largest]) {
            largest = rightChild;
        }

        if(largest != i) {
            swap(arr,largest,i);
            // 递归调整受影响的子树
            heapify(arr, heapSize, largest);
        }

    }

    private static void swap(int[] arr, int l , int r) {
        int temp = arr[l];
        arr[l] = arr[r];
        arr[r] = temp;
    }

}
